package com.bite.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bite.common.core.domain.TableDataInfo;
import com.bite.common.core.domain.dto.BaseQueryTableDTO;
import com.bite.common.core.enums.ResultCode;
import com.bite.common.core.utils.ThreadLocalUtil;
import com.bite.common.security.exception.ServiceException;
import com.bite.friend.domain.exam.vo.ExamVO;
import com.bite.friend.domain.message.Message;
import com.bite.friend.domain.message.MessageText;
import com.bite.friend.domain.message.vo.MessageTextVO;
import com.bite.friend.manager.MessageCacheManager;
import com.bite.friend.mapper.message.MessageMapper;
import com.bite.friend.mapper.message.MessageTextMapper;
import com.bite.friend.service.user.IUserMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Slf4j
@Service
public class UserMessageServiceImpl implements IUserMessageService {

    @Autowired
    private MessageCacheManager messageCacheManager;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private MessageTextMapper messageTextMapper;


    @Override
    public TableDataInfo list(BaseQueryTableDTO queryTableDTO) {
        Long userId = ThreadLocalUtil.getUserId();

        // 从Redis中获取
        Long size = messageCacheManager.getUserMsgListSize(userId);
        if (size == null || size <= 0) {
            // 从数据库获取并刷新缓存
//            List<ExamVO> list = examMapper.list(examQueryDTO);
            messageCacheManager.refreshUserMsgListCache();
        }
        size = messageCacheManager.getUserMsgListSize(userId);
        if (size == null || size <= 0) {
            return TableDataInfo.empty();
        }
        List<MessageTextVO> examVOList = messageCacheManager.getUserMsgList(queryTableDTO);

        return TableDataInfo.success(examVOList, size);
    }

    @Override
    public boolean del(Long textId) {
        if (textId == null) {
            throw new ServiceException(ResultCode.FAILED_MESSAGE_NOT_EXIST);
        }
        try {
            messageCacheManager.delByTextId(textId);
            messageMapper.delete(new LambdaQueryWrapper<Message>()
                    .eq(Message::getTextId, textId));
            messageTextMapper.delete(new LambdaQueryWrapper<MessageText>()
                    .eq(MessageText::getTextId, textId));
            return true;
        } catch (Exception e) {
            log.error("用户消息删除失败 e: {}", e.toString());
            return false;
        }
    }
}
